<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, onMounted, onUnmounted } from 'vue'
import EditModal from '../../common/EditModal.vue'
import { objectToQueryParams } from '@/utils/objectToQuery'
import { formatTableCol, getColWidth, setColWidth, setLastWidth } from '../../common/FormatData'
import { isDate, formatDate } from '@/utils/formatDate'
import * as BasicApi from '@/api/index'

import Pagination from '../../common/Pagination.vue'
import { useMessage } from '@/hooks/useMessage'
const message = useMessage()

// import DetailModal from './DetailModal.vue'
// import BreakdownModal from './BreakdownModal.vue'

// const props = defineProps(['partParams', 'compName'])
const props = defineProps({
  partParams: {
    type: Object
  },
  compName: {
    type: String
  },
  tableInfo: {
    type: Object
  }
})
const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数

const list = ref<any[]>([]) // 列表的数据
const column = ref<any[]>([]) // 列表的表头

const headList = ref<any[]>([]) // 列表的数据

const selectShow = ref() //列表行多选框
const isShowOper = ref() //列表是否有操作
const operList = ref<any[]>([])

const queryParams = reactive({
  type: '',
  value: '',
  keyType: '',
  groupName: '',
  jobType: '',
  pageNo: 1,
  pageSize: 10
})

watch(
  () => props.partParams,
  (val: any) => {
    Object.assign(queryParams, val.inputStr)
    queryParams.groupName && getList()
  }
)

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true
  try {
    const post = {
      ...queryParams
    }
    const inputStr = objectToQueryParams(post)
    const jsonData = props.partParams?.jsonData
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any
    const { code, msg, data, rsCount } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    total.value = rsCount
    if (rsCount == 0) {
      list.value = []
      column.value = []
      operList.value = []
      return
    }
    //格式化数据
    const { listInfo, col } = formatTableCol(data)
    list.value = listInfo || []
    column.value = col || []
    //如果有一项IsShow为true则展示operList
    isShowOper.value =
      data.operInfo &&
      data.operInfo.some((item: any) => item.Value !== 'Select' && item.IsShow == 'true')
    if (isShowOper.value) {
      operList.value =
        data.operInfo &&
        data.operInfo.filter((item: any) => item.Value !== 'Select' && item.IsShow == 'true')
    } else {
      operList.value = []
    }
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['selection-change'])
/** 多选操作 */
const handleSelectionChange = (val: any) => {
  val.length && emit('selection-change', val, headList.value)
}

const modalRef = ref()
/** 编辑弹框 */
const handleEdit = (data: any) => {
  modalRef.value.open(queryParams, data)
}

import eventBus from '@/libs/eventBus'
/** 详情 */
const handleDetail = (data: any) => {
  //打开父组件的详情Tab
  eventBus.emit('addDetailTab', data)
  // localStorage.setItem('WMS_ROW_DATA', JSON.stringify(data))
  // //先判断tag是否存在 存在的话先关闭tag再打开,不存在就正常路由跳转
  // const name = props.compName as any
  // // checkTagExists(name)
  // const post = {
  //   fID: data.FID,
  //   fBillNo: data.FBillNo || '',
  //   type: queryParams.type || ''
  // }
  // const key = name + '_DATA'
  // sessionStorage.setItem(key, JSON.stringify(post))
  // push({
  //   name: props.compName
  // })
}
/** 明细弹框 */
const detailRef = ref()
const breakdownRef = ref()
const handleBreakdown = (data: any) => {
  const { groupName, jobType } = queryParams
  if (groupName == 'BDMgt' && jobType == 'UTR') {
    breakdownRef.value.open(queryParams, data)
  } else {
    detailRef.value.open(queryParams, data)
  }
}

/** 删除按钮操作 */
const handleDelete = async (data: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const inputStr = objectToQueryParams({
      groupName: queryParams.groupName,
      jobType: queryParams.jobType,
      operType: 'Delete'
    })
    const jsonData = props.partParams?.jsonData
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any
    const { code, msg } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    message.success(msg)
    // 刷新列表
    await getList()
  } catch {}
}

// 创建 ref 来引用容器元素
const boxRef = ref()
// 标记容器宽度是否发生变化
const isWidthChanged = ref(false)

const getBoxWidth = () => {
  return boxRef.value?.offsetWidth
}

// 创建 ResizeObserver 实例
let resizeObserver: any
onMounted(() => {
  // 创建 ResizeObserver 实例，传入回调函数
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      // 这里可以编写具体要执行的操作，例如更新状态、发送请求等
      // 这里简单地将 isWidthChanged 设置为 true 表示宽度已变化
      isWidthChanged.value = true
      console.log('容器宽度变化为:', entry.contentRect.width)
      if (entry.contentRect.width) {
        // 可以在这里添加更多操作，比如调用某个函数
        performSpecificOperation(entry.contentRect.width)
      }
    }
  })

  // 开始监听容器元素的尺寸变化
  if (boxRef.value) {
    resizeObserver.observe(boxRef.value)
  }
})

onUnmounted(() => {
  // 当组件卸载时，停止监听并清理资源
  if (resizeObserver && boxRef.value) {
    resizeObserver.unobserve(boxRef.value)
  }
})

// 定义一个具体的操作函数
const performSpecificOperation = (newWidth: any) => {
  console.log('执行了特定操作，新宽度为:', newWidth)
  render(newWidth)
  // 这里可以添加更多复杂的操作，如更新数据、调用 API 等
}

const render = (contentWidth?: number) => {
  const result = props.tableInfo
  let resultWidth = contentWidth ? contentWidth : getBoxWidth()
  //渲染表头
  if (result?.fieldInfo?.length) {
    const columnInfo = JSON.parse(JSON.stringify(result.fieldInfo))
    column.value = columnInfo
    //含有selection则宽度 - 50
    if (selectShow.value) {
      resultWidth = resultWidth - 50
    }
    column.value = getColWidth(column.value, resultWidth)
    setLastWidth(column.value, resultWidth)
  }
  //行操作
  const len = result?.pageInfo?.lineOperate.length
  if (list.value.length && len && result?.fieldInfo?.length) {
    resultWidth = len > 1 ? resultWidth - 120 : resultWidth - 60
    column.value = getColWidth(JSON.parse(JSON.stringify(result.fieldInfo)), resultWidth)
    setLastWidth(column.value, resultWidth)
    operList.value = result?.pageInfo?.lineOperate || []
  }
}

watchEffect(() => {
  render()
})

const refreshList = (width: number) => {
  render(width)
}
eventBus.on('refreshList', refreshList)
</script>
<template>
  <div ref="boxRef">
    <el-table
      v-loading="loading"
      :data="list"
      border
      stripe
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#eaf6fb' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="selectShow" align="center" type="selection" width="50" />
      <template v-for="item in column" :key="item.value">
        <el-table-column
          v-if="item.isShow == 'true'"
          align="center"
          :prop="item.value"
          :label="item.label"
          :width="item.width"
          show-overflow-tooltip
        />
      </template>

      <el-table-column v-if="operList.length" fixed="right" label="操作" align="center" width="120">
        <template #default="scope">
          <template v-for="(item, index) in operList" :key="index">
            <el-button
              v-if="item.value == 'Edit'"
              link
              type="primary"
              @click="handleEdit(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'Detail'"
              link
              type="warning"
              @click="handleDetail(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'Delete'"
              link
              type="danger"
              @click="handleDelete(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'Breakdown'"
              link
              type="success"
              @click="handleBreakdown(list[scope.$index])"
            >
              {{ item.Label }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <Pagination
    class="mt-4"
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
  <!-- 编辑弹框 -->
  <EditModal ref="modalRef" @refresh="getList" />
  <!-- 表单弹窗：只读详情 -->
  <!-- <DetailModal ref="detailRef" /> -->
  <!-- 可编辑的详情 -->
  <!-- <BreakdownModal ref="breakdownRef" /> -->
</template>
<style lang="less" scoped>
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
    background: #eee;
}
/* 自定义表头列之间的边框颜色 */
:deep(.el-table__header th, .el-table__body td) {
  border-right-color: #dfdfdf;
}
:deep(.el-table__cell) {
  border-right-color: #dfdfdf;
}
:deep(.el-table__row--striped .el-table__cell){
  border-right-color: #dfdfdf;
}
</style>
